#include "iuCommandInterface.hpp"
#include <cstdio>
#include <cstring>
#include "iuApplication.hpp"
#include "iuInterface.hpp"

/**
 * @brief Recupere le nom de la commande
 * @return Renvoie le nom de la commande (ici, "interface")
 */
const char *iuCommandInterface::getName() const
{
   static const char *name = "interface";

   return name;
}

/**
 * @brief Execute la commande
 * @param numArgs le nombre d'arguments de la commande
 * @param args les arguments de la commande (args[0] est le nom de la commande)
 * @param app l'application executant la commande
 */
void iuCommandInterface::execute(int numArgs, char **args, iuApplication &app)
{
   //Liste les interfaces
   if (numArgs == 1)
   {
      for (iuInterface *in = app.getInterfaces(); in; in = in->next)
      {
         printf("eth%d %d\n", in->getNumber(), in->getPort());
      }
   }

   //Ajout d'une interface
   else if (numArgs == 3 && strcmp(args[1], "add") == 0)
   {
      int port;

      if (sscanf(args[2], "%d", &port) != 1)
      {
         printf("interface: Invalid argument: the port must be a number\n");
         return;
      }

      app.addInterface(port);
   }

   //Suppression d'une interface
   else if (numArgs == 3 && strcmp(args[1], "del") == 0)
   {
      int number;

      if (sscanf(args[2], "eth%d", &number) != 1)
      {
         printf("interface: Invalid interface name\n");
         return;
      }

      if (!app.delInterface(number))
         printf("interface: No such interface\n");
   }

   //Usage incorrect
   else
   {
      printf("interface: Incorrect usage:\n");
      printf("  interface:           Lists the intefaces\n");
      printf("  interface add 10000: Adds an interface on port 10000\n");
      printf("  interface del eth0:  Deletes the interface eth0\n");
   }
}
